package com.voxel.sense.infomsg.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.L;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.interfaces.listener.onDownloadCallback;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.UploadUtils;

import java.io.File;
import java.util.Locale;

/**
 * Created by ChenYiYao on 2018/1/9.
 */

public class UpdateVersionService extends Service {
    private static final int NOTIFY_ID = 100;
    private static final String CHANNEL = "update";
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotificationManager;
    private String savePath = AppFileUtil.getFileDir() + File.separator + "monitor";//下载存储目录
    private String fileName = "SmartMonitor.apk";
    private boolean isUpdata = false;
    private DownloadTask mPostDownRequest;
    //定义个更新速率，避免更新通知栏过于频繁导致卡顿
    private int rate = -1;
    private onDownloadCallback mCallback;

    @Override
    public IBinder onBind(Intent intent) {
        return new DownloadBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isUpdata = false;
        if (mPostDownRequest != null) {
            mPostDownRequest.remove();
            mPostDownRequest = null;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        L.d("onStartCommand---更新服务");
        return super.onStartCommand(intent, flags, startId);
    }

    private void setNotification() {
        //获取系统通知服务
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this, CHANNEL);
//        //通知标题
        mBuilder.setContentTitle("准备下载新版本");
//        //通知内容
        mBuilder.setContentText("正在连接服务器");
        //设置大图标，即通知条上左侧的图片（如果只设置了小图标，则此处会显示小图标）
//        mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        mBuilder.setSmallIcon( R.mipmap.ic_launcher);
        //设置为不可清除模式
        mBuilder.setOngoing(true);
        mBuilder.setWhen(System.currentTimeMillis());
//        //显示在小图标左侧的数字
//        mBuilder.setNumber（6 ）;
//        //显示通知，ID必须不重复，否则新的通知会覆盖旧的通知（利用这一特性，可以对通知进行更新）
        mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
    }

    public void downApk(String url, onDownloadCallback listener) {
        File file = new File(savePath, fileName);
        mCallback = listener;
        if (FileUtils.isFileExists(file)) {
            FileUtils.deleteFile(file);
        }
        if (isUpdata) {
            //已在更新
            return;
        }
        beginDownload(url);
    }

    private void beginDownload(String url) {
        mPostDownRequest = UploadUtils.getInstent().getPostDownRequest(savePath, fileName, url, new DownloadListener(url) {
            @Override
            public void onStart(Progress progress) {
                setUpdata(true);
                if (mCallback != null) {
                    mCallback.onPrepare();
                }
                setNotification();
            }

            @Override
            public void onProgress(Progress progress) {
                if (mCallback != null) {
                    mCallback.onProgress((int) (progress.fraction * 1000));
                }
                sendNotice((int) (progress.fraction * 100));
            }

            @Override
            public void onError(Progress progress) {
                downloadFinish();
                if (mCallback != null) {
                    mCallback.onFail("下载出错");
                }
                faildNotice();
            }

            @Override
            public void onFinish(File file, Progress progress) {
                downloadFinish();
                mCallback.onComplete(file);

            }

            @Override
            public void onRemove(Progress progress) {
                downloadFinish();
                if (mCallback != null && progress.fraction != 1) {
                    mCallback.onFail("下载出错");
                }
            }

            private void downloadFinish() {
                setUpdata(false);
                mNotificationManager.cancel(NOTIFY_ID);
            }
        });
    }

    public void cancelDown() {
        if (mPostDownRequest != null) {
            mPostDownRequest.pause();
            mPostDownRequest.remove();
            mPostDownRequest = null;
            mNotificationManager.cancel(NOTIFY_ID);
        }
    }


    /**
     * 和activity通讯的binder
     */
    public class DownloadBinder extends Binder {
        public UpdateVersionService getService() {
            return UpdateVersionService.this;
        }
    }

    public boolean isUpdata() {
        return isUpdata;
    }

    public void setUpdata(boolean updata) {
        isUpdata = updata;
    }

    public void sendNotice(int progress) {
        if (rate != progress && mBuilder != null) {
            rate = progress;
            mBuilder.setContentTitle("正在下载：新版本...")
                    .setContentText(String.format(Locale.CHINESE, "%d%%", rate))
                    .setProgress(100, rate, false)
                    .setWhen(System.currentTimeMillis());
            Notification notification = mBuilder.build();
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(NOTIFY_ID, notification);
        }
    }

    public void faildNotice() {
        mBuilder.setContentTitle("版本更新...")
                .setContentText("app下载失败")
                .setProgress(100, rate, false)
                .setWhen(System.currentTimeMillis());
        Notification notification = mBuilder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(NOTIFY_ID, notification);
    }

}
